/*
 * Topol.cpp
 *
 *  Created on: May 12, 2012
 *      Author: marchi
 */

#include "Topol.h"

namespace Topol_NS {
bool myunique(MyResidue & one, MyResidue & two){
	return (one.n==two.n);
}
class op_compare{
	int seq, indx;
public:
	op_compare(int nseq,int nindx):seq(nseq), indx(nindx){};
	op_compare():seq(0),indx(-1){};
	MyResidue operator()(MyResidue m){
		int n=m.n;
		if(indx==-1)indx=n;
		else if(indx != n){
			seq++;
			indx=n;
		}
		m.n=seq;
		return m;
	}
};
Topol::Topol(){
	TypeNames[Slt]="SLT";
	TypeNames[Sol]="SOL";
	TypeNames[Ions]="ION";
	// TODO Auto-generated constructor stub

}
Topol::Topol(const vector<string> & y) {
	TypeNames[Slt]="SLT";
	TypeNames[Sol]="SOL";
	TypeNames[Ions]="ION";
	ExtractInfo(y);
}
Topol & Topol::operator()(const vector<string>& y){
	ExtractInfo(y);
	return *this;
}

Topol::~Topol() {
	// TODO Auto-generated destructor stub
}

void Topol::ExtractInfo(const vector<string> & data){
	atomname.clear();
	resinfo.clear();

	MyResidue mytmp;
	vector<MyResidue> atres;
	int nat=0;
 	for(size_t i=0;i<data.size();i++){
		if(data[i].find("ATOM") != string::npos) {
			string sub1=data[i].substr(11,5);
			string sub2=data[i].substr(17,4);
			string sub3=data[i].substr(72,3);
			std::stringstream(data[i].substr(22,25))>>mytmp.n;

			sub1.erase(remove_if(sub1.begin(),sub1.end(),::isspace),sub1.end());
			sub2.erase(remove_if(sub2.begin(),sub2.end(),::isspace),sub2.end());
			if(sub3.find("WT") != string::npos)
				cidx[Sol].push_back(nat);
			else if(sub3.find("ION") != string::npos)
				cidx[Ions].push_back(nat);
			else
				cidx[Slt].push_back(nat);


			mytmp.name=sub2;
			atomname.push_back(sub1);
			atres.push_back(mytmp);
			nat++;
		}
	}
 	std::transform(atres.begin(),atres.end(),atres.begin(),op_compare());
 	for(unsigned int i=0;i<atres.size();i++){
 		resind.push_back(atres[i].n);
 	}
 	vector<MyResidue>::iterator it=std::unique(atres.begin(),atres.end(),myunique);
 	atres.resize(it-atres.begin());


 	for(unsigned int i=0;i<atres.size();i++){
 		resinfo.push_back(atres[i].name);
 	}
 	nr=atomname.size();
 	nres=atres.size();
 	cout << std::fixed << std::setw(6)<< "\n Topology extracted from pdb file. Number of atoms: "
 			<< nr << " Nmber of residue: " << nres << "\n\n";
}
} /* namespace Topol_NS */
